<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="nav-item" @click="handleCancel" :class="{ 'disabled': isFormEmpty }">取消</view>
			<view class="nav-title">{{ currentPage === 1 ? '编辑内容' : '设置' }}</view>
			<view class="nav-item" v-if="currentPage === 1" @click="toNextPage" :class="{ 'disabled': blogData.title.length < 10 }">{{ blogData.title.length < 10 ? '标题至少10字' : '下一步' }}</view>
			<view class="nav-item" v-else @click="toPrevPage">上一步</view>
		</view>

		<!-- 表单内容 - 第一页 -->
		<scroll-view class="content" scroll-y="true" v-if="currentPage === 1">
			<!-- 标题输入 -->
			<view class="form-item">
				<input class="title-input" v-model="blogData.title" type="text" placeholder="请输入标题（5~100字）"
					maxlength="100" placeholder-style="color: #cccccc;" />
				<text class="title-length">{{ blogData.title.length }}/100</text>
			</view>

			<!-- 正文编辑 -->
			<view class="form-item">
				<!-- 编辑器工具栏 -->
				<view class="editor-toolbar">
					<view class="tool-item" @click="format('bold')">
						<text>𝐁</text>
					</view>
					<view class="tool-item" @click="format('italic')">
						<text>𝑰</text>
					</view>
					<view class="tool-item" @click="format('underline')">
						<text>𝐔</text>
					</view>
					<view class="tool-item" @click="insertImage">
						<image src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
					</view>
					<view class="tool-item" @click="format('align', 'left')">
						<text>左</text>
					</view>
					<view class="tool-item" @click="format('align', 'center')">
						<text>中</text>
					</view>
					<view class="tool-item" @click="format('align', 'right')">
						<text>右</text>
					</view>
				</view>

				<!-- 编辑器内容区 -->
				<editor
					v-model="blogData.content"
					class="content-editor"
					placeholder="请输入正文内容"
					placeholder-style="color: #cccccc;"
					@ready="onEditorReady"
					@input="onEditorInput"
				></editor>
			</view>
		</scroll-view>

		<!-- 表单内容 - 第二页 -->
		<scroll-view class="content" scroll-y="true" v-else>
			<!-- 封面设置 -->
				<view class="form-item">
					<view class="form-label">封面</view>
					<view class="radio-group">
						<view class="radio-item" :class="{ 'radio-item-active': blogData.hasCover }"
							@click="blogData.hasCover = true">
							<view class="radio-circle">
								<view v-if="blogData.hasCover" class="radio-dot"></view>
							</view>
							<text>有封面</text>
						</view>
						<view class="radio-item" :class="{ 'radio-item-active': !blogData.hasCover }"
							@click="blogData.hasCover = false">
							<view class="radio-circle">
								<view v-if="!blogData.hasCover" class="radio-dot"></view>
							</view>
							<text>无封面</text>
						</view>
					</view>
				</view>

				<!-- 封面上传区域（仅当选择有封面时显示） -->
				<view class="form-item" v-if="blogData.hasCover">
					<view class="cover-uploader">
						<view v-if="!blogData.coverUrl" class="upload-btn" @click="handleCoverUpload">
							<image src="/static/icons/wechat-icon.svg" mode="aspectFit"></image>
							<text>上传封面</text>
						</view>
						<view v-else class="cover-preview">
							<image :src="blogData.coverUrl" mode="aspectFill"></image>
							<view class="delete-btn" @click="handleCoverDelete"></view>
						</view>
						<text class="upload-tip">仅支持一张封面，建议尺寸16:9</text>
					</view>
				</view>

			<!-- 文章标签 -->
			<view class="form-item">
				<view class="form-label">文章标签</view>
				<view class="tags-container">
					<view class="tag-item" v-for="(tag, index) in blogData.tags" :key="index">
						<text>{{ tag }}</text>
						<view class="tag-delete" @click.stop="handleTagDelete(index)"></view>
					</view>

					<!-- 添加文章标签按钮 -->
					<view class="add-tag-btn" @click="showTagDialog">
						<text>+ 添加文章标签</text>
					</view>
				</view>
				<text class="upload-tip">最多添加5个标签</text>
			</view>

			<!-- 标签选择弹窗 -->
			<view v-if="showTagModal" class="tag-dialog-overlay" @click="closeTagDialog">
				<view class="tag-dialog" @click.stop>
					<view class="tag-dialog-header">
						<text class="tag-dialog-title">标签</text>
						<view class="tag-dialog-close" @click="closeTagDialog"></view>
					</view>
					<view class="tag-dialog-content">
						<input v-model="tagSearchText" type="text" class="tag-search-input"
							placeholder="请输入文字搜索，Enter键可添加自定义标签" placeholder-style="color: #cccccc;"
							@confirm="handleCustomTagAdd" />

						<!-- 显示搜索结果或全部标签 -->
						<view v-if="filteredCategories.length > 0">
							<view v-for="(category, index) in filteredCategories" :key="index" class="tag-category">
								<text class="category-title">{{ category.name }}</text>
								<view class="category-tags">
									<view v-for="(tag, tagIndex) in category.children" :key="tagIndex" class="category-tag"
										:class="{ 'tag-selected': blogData.tags.includes(tag.name) }"
										@click="handleSelectTag(tag)">
										{{ tag.name }}
									</view>
								</view>
							</view>
						</view>

						<!-- 无搜索结果提示 -->
						<view v-else-if="tagSearchText.trim()" class="no-results">
							<text>暂无匹配的标签</text>
						</view>

						<text class="tag-count">还可添加{{ 5 - blogData.tags.length }}个标签</text>
					</view>
				</view>
			</view>

			<!-- 文章摘要 -->
			<view class="form-item">
				<view class="form-label">摘要</view>
				<textarea class="summary-textarea" v-model="blogData.subtitle" placeholder="请输入文章摘要（最多200字）"
					placeholder-style="color: #cccccc;" maxlength="200" auto-height="true"></textarea>
			</view>

			<!-- 文章类型 -->
			<view class="form-item">
				<view class="form-label">文章类型</view>
				<view class="radio-group">
					<view class="radio-item" :class="{ 'radio-item-active': blogData.type === 1 }"
						@click="blogData.type = 1">
						<view class="radio-circle">
							<view v-if="blogData.type === 1" class="radio-dot"></view>
						</view>
						<text>原创</text>
					</view>
					<view class="radio-item" :class="{ 'radio-item-active': blogData.type === 2 }"
						@click="blogData.type = 2">
						<view class="radio-circle">
							<view v-if="blogData.type === 2" class="radio-dot"></view>
						</view>
						<text>转载</text>
					</view>
					<view class="radio-item" :class="{ 'radio-item-active': blogData.type === 3 }"
						@click="blogData.type = 3">
						<view class="radio-circle">
							<view v-if="blogData.type === 3" class="radio-dot"></view>
						</view>
						<text>翻译</text>
					</view>
				</view>
			</view>

			<!-- 可见范围 -->
			<view class="form-item">
				<view class="form-label">可见范围</view>
				<view class="radio-group">
					<view class="radio-item" :class="{ 'radio-item-active': blogData.visibility === 1 }"
						@click="blogData.visibility = 1">
						<view class="radio-circle">
							<view v-if="blogData.visibility === 1" class="radio-dot"></view>
						</view>
						<text>全部可见</text>
					</view>
					<view class="radio-item" :class="{ 'radio-item-active': blogData.visibility === 2 }"
						@click="blogData.visibility = 2">
						<view class="radio-circle">
							<view v-if="blogData.visibility === 2" class="radio-dot"></view>
						</view>
						<text>仅我可见</text>
					</view>
					<view class="radio-item" :class="{ 'radio-item-active': blogData.visibility === 3 }"
						@click="blogData.visibility = 3">
						<view class="radio-circle">
							<view v-if="blogData.visibility === 3" class="radio-dot"></view>
						</view>
						<text>粉丝可见</text>
					</view>
				</view>
			</view>
		</scroll-view>


		<!-- 底部操作栏 - 第二页 -->
		<view class="bottom-bar" v-if="currentPage === 2">
			<view class="action-btn" @click="handleSaveDraft">保存草稿</view>
			<view class="action-btn primary" @click="handlePublish">发布内容</view>
		</view>

		<!-- 定时发布弹窗 -->
		<view class="modal" v-if="showScheduleModal" @click="showScheduleModal = false">
			<view class="modal-content" @click.stop>
				<view class="modal-title">定时发布</view>
				<view class="datetime-picker">
					<picker mode="datetime" :value="scheduleTime" start="2023-01-01 00:00" end="2025-12-31 23:59"
						@change="onScheduleTimeChange">
						<view class="picker-item">
							{{ scheduleTime || '请选择发布时间' }}
						</view>
					</picker>
				</view>
				<view class="modal-buttons">
					<view class="modal-btn" @click="showScheduleModal = false">取消</view>
					<view class="modal-btn modal-btn-primary" @click="confirmSchedulePublish">确认</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {getBlogTags} from "@/api/blog-publish";
	import blogPublishApi from '../../api/blog-publish.js';

	export default {
		data() {
			return {
				currentPage: 1, // 当前页面，1表示第一页，2表示第二页
				blogData: {
					title: '',
					coverUrl: '',
					subtitle: '',
					content: '',
					images: [],
					// tagsId: [],
					tags: [],
					type: 1, // 1, 2, 3
					visibility: 1, // 1, 2, 3
					articleId: '',
					status: true,
					isScheduled: false,
					hasCover: true // true表示有封面，false表示无封面
				},
				tempTag: '',
				showScheduleModal: false,
				scheduleTime: '',
				loading: false,
				// 标签相关数据
				showTagModal: false,
				tagSearchText: '',
				tagCategories: [],
				// 编辑器上下文
				editorCtx: null
			};
		},

		computed: {
			// 过滤后的标签分类
			filteredCategories() {
				if (!this.tagSearchText.trim()) {
					// 没有输入时显示全部标签
					return this.tagCategories;
				}

				const searchText = this.tagSearchText.toLowerCase().trim();

				// 处理树形结构数据的过滤函数
				const filterCategories = (categories) => {
					return categories.map(category => {
						// 复制当前分类
						const filteredCategory = { ...category };
						// 处理子分类
						if (category.children && category.children.length > 0) {
							const filteredChildren = filterCategories(category.children);
							// 只保留有匹配子分类的
							if (filteredChildren.length > 0) {
								filteredCategory.children = filteredChildren;
							}
						}
						// 检查当前分类名称是否匹配
						const nameMatch = category.name.toLowerCase().includes(searchText);
						// 检查是否有子分类匹配
						const hasMatchedChildren = filteredCategory.children && filteredCategory.children.length > 0;
						// 只有当名称匹配或有匹配子分类时才返回
						return nameMatch || hasMatchedChildren ? filteredCategory : null;
					}).filter(Boolean);
				};

				return filterCategories(this.tagCategories);
			}
		},

		onLoad(options) {
			// 如果有草稿ID，则加载草稿
			if (options.articleId) {
				this.loadDraft(options.articleId);
			}

			// 获取分类标签集合
			this.getBlogTags();
		},

		methods: {
			/**
			 * 加载草稿
			 */
			async loadDraft(articleId) {
				try {
					this.loading = true;
					const res = await blogPublishApi.getDraftDetail(articleId);
					if (res.code === 0) {
						this.blogData = {
							...res.data,
							images: res.data.images || []
						};
					} else {
						uni.showToast({
							title: res.message || '加载草稿失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载草稿失败:', error);
					uni.showToast({
						title: '加载草稿失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			/**
			 * 处理取消按钮点击
			 */
			handleCancel() {
				// 检查是否有未保存的内容
				if (this.hasUnsavedChanges()) {
					uni.showModal({
						title: '提示',
						content: '内容尚未保存，确定要取消吗？',
						success: (res) => {
							if (res.confirm) {
								this.handleConfirmCancel();
							}
						}
					});
				} else {
					this.handleConfirmCancel();
				}
			},

			/**
			 * 确认取消操作
			 */
			async handleConfirmCancel() {
				this.currentPage = 1; // 显示第一页
				
				if (this.blogData.articleId) {
					// 当存在博客编号时，重新检索数据
					try {
						this.loading = true;
						const res = await blogPublishApi.getDraftDetail(this.blogData.articleId);
						if (res.code === 0) {
							this.blogData = {
								...res.data,
								images: res.data.images || [],
								articleId: this.blogData.articleId // 保留原始articleId
							};
						} else {
							uni.showToast({
								title: res.message || '加载草稿失败',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('加载草稿失败:', error);
						uni.showToast({
							title: '加载草稿失败',
							icon: 'none'
						});
					} finally {
						this.loading = false;
					}
				} else {
					// 当不存在博客编号时，清空数据
					this.blogData = {
						title: '',
						coverUrl: '',
						subtitle: '',
						content: '',
						images: [],
						tagsId: [],
						type: 1,
						visibility: 1,
						articleId: '',
						status: true,
						isScheduled: false
					};
				}
			},

			/**
			 * 检查是否有未保存的内容
			 */
			hasUnsavedChanges() {
				return this.blogData.title.trim() !== '' ||
					this.blogData.content.trim() !== '' ||
					this.blogData.coverUrl !== '' ||
					this.blogData.tagsId.length > 0 ||
					this.blogData.subtitle.trim() !== '';
			},

			/**
			 * 判断表单是否为空（用于禁用取消按钮）
			 */
			isFormEmpty() {
				return this.blogData.title.trim() === '' &&
					this.blogData.content.trim() === '' &&
					this.blogData.coverUrl === '' &&
					this.blogData.tagsId.length === 0 &&
					this.blogData.subtitle.trim() === '' &&
					!this.blogData.articleId;
			},

			/**
			 * 切换到下一页
			 */
			toNextPage() {
				if (this.blogData.title.length < 10) {
					uni.showToast({
						title: '标题至少需要10个文字',
						icon: 'none'
					});
					return;
				}
				this.currentPage = 2;
			},

			/**
			 * 切换到上一页
			 */
			toPrevPage() {
				this.currentPage = 1;
			},

			/**
			 * 处理发布按钮点击
			 */
			async handlePublish() {
				// 表单验证
				if (!this.validateForm()) return;

				try {
					this.loading = true;
					const res = await blogPublishApi.publishBlog(this.blogData);
					if (res.code === 0) {
						uni.showToast({
							title: '发布成功',
							icon: 'success'
						});
						// 发布成功后返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.message || '发布失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('发布失败:', error);
					uni.showToast({
						title: '发布失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			/**
			 * 处理保存草稿按钮点击
			 */
			async handleSaveDraft() {
				try {
					this.loading = true;
					const res = await blogPublishApi.saveDraft(this.blogData);
					if (res.code === 0) {
						this.blogData.articleId = res.data.articleId;
						uni.showToast({
							title: '草稿保存成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: res.message || '保存草稿失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('保存草稿失败:', error);
					uni.showToast({
						title: '保存草稿失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			/**
			 * 处理定时发布按钮点击
			 */
			handleSchedulePublish() {
				// 表单验证
				if (!this.validateForm()) return;

				// 设置默认时间为当前时间
				if (!this.scheduleTime) {
					const now = new Date();
					this.scheduleTime = this.formatDateTime(now);
				}

				this.showScheduleModal = true;
			},

			/**
			 * 确认定时发布
			 */
			async confirmSchedulePublish() {
				if (!this.scheduleTime) {
					uni.showToast({
						title: '请选择发布时间',
						icon: 'none'
					});
					return;
				}

				try {
					this.loading = true;
					const res = await blogPublishApi.schedulePublish(this.blogData, this.scheduleTime);
					if (res.code === 0) {
						this.showScheduleModal = false;
						uni.showToast({
							title: '已设置定时发布',
							icon: 'success'
						});
						// 定时发布设置成功后返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.message || '设置定时发布失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('设置定时发布失败:', error);
					uni.showToast({
						title: '设置定时发布失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			/**
			 * 定时发布时间选择变化
			 */
			onScheduleTimeChange(e) {
				this.scheduleTime = e.detail.value;
			},

			/**
			 * 处理封面上传
			 */
			async handleCoverUpload() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						const tempFilePath = res.tempFilePaths[0];
						try {
							// 显示加载提示
							uni.showLoading({
								title: '上传中...'
							});

							// 上传封面
							const uploadRes = await blogPublishApi.uploadImage(tempFilePath, 'cover');

							// 隐藏加载提示
							uni.hideLoading();

							if (uploadRes.code === 0) {
								this.blogData.coverUrl = uploadRes.data.imageUrl;
								uni.showToast({
									title: '上传成功',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: uploadRes.message || '上传失败',
									icon: 'none'
								});
							}
						} catch (error) {
							uni.hideLoading();
							console.error('上传封面失败:', error);
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
				});
			},

			/**
			 * 处理封面删除
			 */
			handleCoverDelete() {
				uni.showModal({
					title: '提示',
					content: '确定要删除封面吗？',
					success: (res) => {
						if (res.confirm) {
							this.blogData.coverUrl = '';
						}
					}
				});
			},

			/**
			 * 处理图片上传
			 */
			async handleImageUpload() {
				// 检查是否已达到图片数量上限
				if (this.blogData.images.length >= 9) {
					uni.showToast({
						title: '最多上传9张图片',
						icon: 'none'
					});
					return;
				}

				uni.chooseImage({
					count: 9 - this.blogData.images.length,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						const tempFilePaths = res.tempFilePaths;

						try {
							// 显示加载提示
							uni.showLoading({
								title: '上传中...'
							});

							// 批量上传图片
							const uploadPromises = tempFilePaths.map(path =>
								blogPublishApi.uploadImage(path, 'article')
							);

							const uploadResults = await Promise.all(uploadPromises);

							// 隐藏加载提示
							uni.hideLoading();

							// 处理上传结果
							const successImages = [];
							uploadResults.forEach(result => {
								if (result.code === 0) {
									successImages.push(result.data.imageUrl);
								}
							});

							if (successImages.length > 0) {
								this.blogData.images = [...this.blogData.images, ...successImages];
								uni.showToast({
									title: `成功上传${successImages.length}张图片`,
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: '图片上传失败',
									icon: 'none'
								});
							}
						} catch (error) {
							uni.hideLoading();
							console.error('上传图片失败:', error);
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
				});
			},

			/**
			 * 编辑器初始化完成
			 */
			onEditorReady() {
				uni.createSelectorQuery()
					.in(this)
					.select('.content-editor')
					.context(res => {
						this.editorCtx = res.context;
					})
					.exec();
			},

			/**
			 * 编辑器内容变化
			 */
			onEditorInput(e) {
				this.blogData.content = e.detail.html;
			},

			/**
			 * 格式化文本
			 */
			format(name, value) {
				if (!this.editorCtx) return;
				this.editorCtx.format(name, value);
			},

			/**
			 * 插入图片
			 */
			insertImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						const tempFilePath = res.tempFilePaths[0];

						try {
							// 显示加载提示
							uni.showLoading({
								title: '上传中...'
							});

							// 上传图片
							const uploadRes = await blogPublishApi.uploadImage(tempFilePath, 'article');

							// 隐藏加载提示
							uni.hideLoading();

							if (uploadRes.code === 0) {
								const imageUrl = uploadRes.data.imageUrl;
								// 在编辑器中插入图片
								this.editorCtx.insertImage({
									src: imageUrl,
									width: '100%',
									height: 'auto'
								});
								// 将图片添加到images数组中
								this.blogData.images.push(imageUrl);
							} else {
								uni.showToast({
									title: uploadRes.message || '上传失败',
									icon: 'none'
								});
							}
						} catch (error) {
							uni.hideLoading();
							console.error('上传图片失败:', error);
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					}
				});
			},

			/**
			 * 处理图片删除
			 */
			handleImageDelete(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					success: (res) => {
						if (res.confirm) {
							this.blogData.images.splice(index, 1);
						}
					}
				});
			},

			/**
			 * 获取标签集合
			 */
			async getBlogTags() {
				try {
					const data = await getBlogTags();
					if (data.code === 0) {
						// 处理树形结构的标签数据
						this.tagCategories = data.data
					}
				} catch (error) {
					console.error('获取标签失败:', error);
				}

			},

			/**
			 * 处理标签添加
			 */
			handleTagAdd() {
				const tag = this.tempTag.trim();
				if (tag && this.blogData.tags.length < 5 && !this.blogData.tags.includes(tag)) {
					this.blogData.tags.push(tag);
					this.tempTag = '';
				}
			},

			/**
			 * 显示标签选择弹窗
			 */
			showTagDialog() {
				this.showTagModal = true;
				this.tagSearchText = '';
			},

			/**
			 * 关闭标签选择弹窗
			 */
			closeTagDialog() {
				this.showTagModal = false;
				this.tagSearchText = '';
			},

			/**
			 * 处理标签选择
			 */
			handleSelectTag(tag) {
				if (this.blogData.tags.includes(tag.name)) {
					// 取消选择
					const index = this.blogData.tags.indexOf(tag.name);
					this.blogData.tags.splice(index, 1);
				} else {
					// 添加选择
					if (this.blogData.tags.length < 5) {
						this.blogData.tags.push(tag.name);
					} else {
						uni.showToast({
							title: '最多添加5个标签',
							icon: 'none'
						});
					}
				}
			},

			/**
			 * 处理自定义标签添加
			 */
			handleCustomTagAdd() {
				const tag = this.tagSearchText.trim();
				if (tag && this.blogData.tags.length < 5 && !this.blogData.tags.includes(tag)) {
					this.blogData.tags.push(tag);
					this.tagSearchText = '';
				} else if (this.blogData.tags.length >= 5) {
					uni.showToast({
						title: '最多添加5个标签',
						icon: 'none'
					});
				}
			},

			/**
			 * 处理标签删除
			 */
			handleTagDelete(index) {
				this.blogData.tags.splice(index, 1);
			},

			/**
			 * 表单验证
			 */
			validateForm() {
				if (!this.blogData.title.trim()) {
					uni.showToast({
						title: '请输入标题',
						icon: 'none'
					});
					return false;
				}

				if (!this.blogData.content.trim()) {
					uni.showToast({
						title: '请输入正文内容',
						icon: 'none'
					});
					return false;
				}

				return true;
			},

			/**
			 * 格式化日期时间
			 */
			formatDateTime(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;
			}
		}
	};
</script>

<style lang="scss">
	@import './blog-publish.scss';
</style>